import React, { useEffect, useState } from 'react';
import { ScrollView } from 'react-native';
import {
  List,
  Checkbox,
  Button,
  Toast,
  InputItem,
} from '@ant-design/react-native';
import PhotoCameraPicker from '@/rcomponents/photoCameraPicker';
import UserStore from '@/stores/userStore';
import { formatDate } from '@/helpers/dateutil';
import ReleaseJobStore from './releaseJobStore';

// 航线放行确认/信息查看页面
function FlightReleasePassPage({ navigation, route }) {
  const userStore = UserStore.useStore();
  const [passConfirms, setPassConfirms] = useState([
    {
      key: 'safetypinon',
      text: '起落架安全销装上',
      value: '3',
      checked: false,
    },
    {
      key: 'pilottubeon',
      text: '空速管套装上',
      value: '4',
      checked: false,
    },
    {
      key: 'safetypin',
      text: '起落架安全销取下',
      value: '5',
      checked: false,
    },
    {
      key: 'pilottube',
      text: '空速管套取下',
      value: '6',
      checked: false,
    },
    {
      key: 'oil',
      text: '滑油口盖盖上锁紧',
      value: '7',
      checked: false,
    },
    {
      key: 'signed',
      text: '工作单完成并签署',
      value: '8',
      checked: false,
    },
    {
      key: 'failurexclude',
      text: '故障缺陷已保留或排除',
      value: '9',
      checked: false,
    },
  ]);

  const [formValue, setFormValue] = useState({
    oiladd1: '0',
    oiladd2: '0',
    filesUrl: '',
  });
  const rjStore = ReleaseJobStore.useStore();
  useEffect(() => {
    const newPassConfirms = [];
    for (let i = 0; i < passConfirms.length; i++) {
      if (
        route.params.taskPaperType !== 'AF' &&
        passConfirms[i].value !== '3' &&
        passConfirms[i].value !== '4'
      ) {
        newPassConfirms.push({
          ...passConfirms[i],
        });
      } else if (
        route.params.taskPaperType === 'AF' &&
        passConfirms[i].value !== '5' &&
        passConfirms[i].value !== '6'
      ) {
        newPassConfirms.push({
          ...passConfirms[i],
        });
      }
    }
    if (rjStore.flightPassInfo) {
      setFormValue({
        oiladd1: rjStore.flightPassInfo.oiladd1,
        oiladd2: rjStore.flightPassInfo.oiladd2,
      });
      const checkValue = rjStore.flightPassInfo.checkValue.split(',');
      for (let i = 0; i < newPassConfirms.length; i++) {
        newPassConfirms[i].checked = checkValue.includes(
          newPassConfirms[i].value,
        );
      }
    }
    setPassConfirms(newPassConfirms);
    // setPhotos
  }, [rjStore]);
  const handlePass = async () => {
    const paraChecks = passConfirms
      .filter((rtc) => rtc.checked)
      .map((rtc) => rtc.value)
      .join(',');
    if (paraChecks.length !== 9) {
      Toast.fail('检查单未确认完毕，需要全选');
      return;
    }
    const paraVerify = await rjStore.verifyPass(
      userStore.user.LoginName,
      route.params.taskStageTid,
      route.params.flightTid,
    );
    if (paraVerify.data !== true) {
      Toast.fail(paraVerify.errorMsg.replace(/[\'\"\\\/\b\f\nn\r\t]/g, '\n'));
      return;
    }

    const passPara = {
      taskStageTid: route.params.taskStageTid,
      flightTid: route.params.flightTid,
      checkValue: paraChecks,
      filesUrl: formValue.filesUrl,
      taskType: '航线',
      oiladd1: formValue.oiladd1,
      oiladd2: formValue.oiladd2,
    };
    const res = await rjStore.passTask(userStore.user.LoginName, passPara);
    if (res.errorCode) {
      Toast.fail(res.errorMsg);
      return;
    }
    navigation.goBack();
  };
  return (
    <>
      <ScrollView keyboardShouldPersistTaps={'always'} nestedScrollEnabled>
        <List renderHeader="放行确认单">
          {passConfirms.map((retcat) => (
            <Checkbox.CheckboxItem
              key={retcat.key}
              checked={retcat.checked}
              disabled={!!rjStore.flightPassInfo}
              onChange={(event) => {
                setPassConfirms(
                  passConfirms.map((retc) => {
                    if (retc.key === retcat.key) {
                      return { ...retc, checked: event.target.checked };
                    }
                    return retc;
                  }),
                );
              }}
            >
              {retcat.text}
            </Checkbox.CheckboxItem>
          ))}
          <List.Item
            extra={
              <PhotoCameraPicker
                disabled={!!rjStore.flightPassInfo}
                onFileChange={(file) => {
                  const fileObj = JSON.parse(file);
                  setFormValue({
                    filesUrl: [formValue.filesUrl, fileObj.FilePath]
                      .filter((f) => f)
                      .join(','),
                  });
                }}
              />
            }
          >
            图片
          </List.Item>
        </List>
        <List renderHeader="滑油添加量">
          <InputItem
            value={formValue.oiladd1}
            editable={!rjStore.flightPassInfo}
            onChange={(val) => {
              setFormValue({ ...formValue, oiladd1: val });
            }}
            labelNumber={5}
          >
            左发(夸脱)
          </InputItem>
          <InputItem
            editable={!rjStore.flightPassInfo}
            value={formValue.oiladd2}
            onChange={(val) => {
              setFormValue({ ...formValue, oiladd2: val });
            }}
            labelNumber={5}
          >
            右发(夸脱)
          </InputItem>
        </List>
        {!!rjStore.flightPassInfo && (
          <List renderHeader="放行信息">
            <List.Item extra={rjStore.flightPassInfo.Name}>放行人员</List.Item>
            <List.Item
              extra={formatDate(
                rjStore.flightPassInfo.date,
                'YYYY-MM-DD HH:mm:ss',
              )}
            >
              放行时间
            </List.Item>
            <List.Item extra="">已放行</List.Item>
          </List>
        )}
      </ScrollView>
      {!rjStore.flightPassInfo && (
        <Button
          type="primary"
          onPress={handlePass}
          loading={rjStore.passTask.loading}
        >
          放行
        </Button>
      )}
    </>
  );
}

FlightReleasePassPage.routeName = 'FlightReleasePassPage';
FlightReleasePassPage.permission = 'RFlightPass';
export default FlightReleasePassPage;
